package com.suray.attendance.db.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.db.mapper.ReportWorkInfoMapper;
import com.suray.attendance.db.service.ErpOperationInfoDBService;
import com.suray.attendance.db.service.ReportWorkInfoDBService;
import com.suray.attendance.model.bean.Mo;
import com.suray.attendance.model.enums.erp.server.RequestServerProdEnum;
import com.suray.attendance.model.pojo.ProductionDataCollectDetailInfo;
import com.suray.attendance.model.bean.ProductionDataCollectInfo;
import com.suray.attendance.model.enums.erp.ErpApiServerNameEnum;
import com.suray.attendance.model.pojo.ReportWorkInfo;
import com.suray.attendance.model.vo.ProductionDataCollectDetailVo;
import com.suray.attendance.model.vo.ProductionDataCollectVo;
import com.suray.attendance.service.ErpService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 * @author jly
 * @since 2023-09-20
 */
@Service
public class ReportWorkInfoDBServiceImpl extends ServiceImpl<ReportWorkInfoMapper, ReportWorkInfo> implements ReportWorkInfoDBService {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Resource
    private ReportWorkInfoMapper reportWorkInfoMapper;
    @Resource
    private ErpService erpService;
    @Resource
    private ErpOperationInfoDBService erpOperationInfoDBService;




    @Override
    public Boolean updateReportWorkInfoDataSyncStatus(List<ReportWorkInfo> reportWorkInfoList, Integer dataSyncStatus) {
        try {
            baseMapper.updateBatch(reportWorkInfoList,dataSyncStatus);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.error("批量修改"+ JSON.toJSONString(reportWorkInfoList)+"的数据同步状态为"+dataSyncStatus+"失败，异常信息为"+e.getMessage(),ReportWorkInfoDBServiceImpl.class);
            throw new RuntimeException("批量修改"+ JSON.toJSONString(reportWorkInfoList)+"的数据同步状态为"+dataSyncStatus+"失败，异常信息为"+e.getMessage());
        }
    }
    @Override
    public Boolean workReportDataToErp(List<ProductionDataCollectVo> productionData) {
        if(productionData==null || productionData.size()==0){
            return false;
        }
        try {
            List<ProductionDataCollectInfo> productionDataCollectInfoList = productionData.stream().map(productionDataCollectVo -> {
                ProductionDataCollectInfo productionDataCollectInfo = new ProductionDataCollectInfo();
                productionDataCollectInfo.setCollect_times(LocalDateTime.now().format(dateTimeFormatter));
                String employee_no = productionDataCollectVo.getEmployeeNo();
                productionDataCollectInfo.setEmployee_no(employee_no);
                String factoryCode = productionDataCollectVo.getFactoryCode();
                productionDataCollectInfo.setOm_site_id(factoryCode);
                productionDataCollectInfo.setWorkstation_no(factoryCode + 40000);
                productionDataCollectInfo.setRemark("研发报工");
                List<ProductionDataCollectDetailInfo> productionDataCollectDetailInfoListSum = new ArrayList<>();
                Map<String, List<ProductionDataCollectDetailVo>> collect = productionDataCollectVo.getProductionDataCollectDetailVoList()
                        .stream().collect(Collectors.groupingBy(ProductionDataCollectDetailVo::getProjectReportErpCode));
                if (collect != null && collect.size() > 0) {
                    AtomicInteger atomicInteger = new AtomicInteger(1);
                    Iterator<Map.Entry<String, List<ProductionDataCollectDetailVo>>> iterator = collect.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<ProductionDataCollectDetailVo>> next = iterator.next();
                        String projectReportErpCode = next.getKey();
                        // 查询研发报工单
                        List<String[]> queryMaps = new ArrayList<String[]>();
                        queryMaps.add(new String[]{"project_no", projectReportErpCode, "="});
                        queryMaps.add(new String[]{"om_site_id", factoryCode, "="});
                        List<String[]> orderMaps = new ArrayList<String[]>();
                        orderMaps.add(new String[]{"doc_no", "desc"});
                        List<Object> objectList = erpService.queryCondition(ErpApiServerNameEnum.维护工单.name(), queryMaps, orderMaps, RequestServerProdEnum.OAPI正式.getRequestProd());
                        if(objectList!=null&&objectList.size()>0){
                            Mo mo = JSONObject.parseObject(JSON.toJSONString(objectList.get(0)), Mo.class);
                            if (mo != null && !StringUtils.isEmpty(mo.getDoc_no())) {
                                String doc_no = mo.getDoc_no();
                                List<ProductionDataCollectDetailVo> productionDataCollectDetailVoList = next.getValue();
                                List<ProductionDataCollectDetailInfo> productionDataCollectDetailInfoList = productionDataCollectDetailVoList.stream().map(productionDataCollectDetailVo -> {
                                    ProductionDataCollectDetailInfo productionDataCollectDetailInfo = new ProductionDataCollectDetailInfo();
                                    productionDataCollectDetailInfo.setDoc_no_seq(atomicInteger.getAndIncrement());
                                    String employeeNo = productionDataCollectDetailVo.getEmployeeNo();
                                    Long laborHours = productionDataCollectDetailVo.getLaborHours();
                                    String pieceType = productionDataCollectDetailVo.getPieceType();
                                    String unitNo = productionDataCollectDetailVo.getUnitNo();
                                    BigDecimal qty = productionDataCollectDetailVo.getQty();
                                    String technologyCode = erpOperationInfoDBService.getIdByOperationCode(productionDataCollectDetailVo.getTechnologyCode()).getOperationId();
                                    String productionDate = productionDataCollectDetailVo.getProductionDate();
                                    productionDataCollectDetailInfo.setEmployee_no(employeeNo);
                                    productionDataCollectDetailInfo.setLabor_hours(laborHours);
                                    productionDataCollectDetailInfo.setPiece_type(pieceType);
                                    productionDataCollectDetailInfo.setUnit_no(unitNo);
                                    productionDataCollectDetailInfo.setWo_no(doc_no);
                                    productionDataCollectDetailInfo.setQty(qty);
                                    productionDataCollectDetailInfo.setTechnology_code(technologyCode);
                                    productionDataCollectDetailInfo.setProduction_date(productionDate);
                                    return productionDataCollectDetailInfo;
                                }).collect(Collectors.toList());
                                productionDataCollectDetailInfoListSum.addAll(productionDataCollectDetailInfoList);
                            }else{
                                LoggerUtil.warn(projectReportErpCode+factoryCode+"数据异常无法查询到研发工单的数据",ReportWorkInfoDBServiceImpl.class);
                            }
                        }
                    }
                    productionDataCollectInfo.setSF_DATA_COLLECT_D(productionDataCollectDetailInfoListSum);
                }
                return productionDataCollectInfo;
            }).collect(Collectors.toList());
            Map<String, Object> addResponse = erpService.add(ErpApiServerNameEnum.维护生产信息收集单.name(), ProductionDataCollectInfo.toJSONString(productionDataCollectInfoList),RequestServerProdEnum.OAPI正式.getRequestProd());
            if(addResponse!=null && addResponse.size()>0){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.error("处理新增研发报工信息异常"+e.getMessage(),ReportWorkInfoDBServiceImpl.class);
            throw new RuntimeException("处理新增研发报工信息异常"+e.getMessage());
        }
        return false;
    }

}
